export interface GameStorageData {
    // userId: string;
    // nickName: string;
    // avatar: string;

    // sound_on: boolean;
    // music_on: boolean;

    high_score: number;
    high_score_lastTime: number;
    GameData: any;

    /** 解锁角色 */
    unlock_list_role: number[];

    select_index_role: number;
}

/** 存储类，用于存储需要本地保存的数据 */
class GameStorage {
    data: GameStorageData = null;
    defaultValue: GameStorageData = null;

    private static _instance: GameStorage = null;

    static get instance(): GameStorage {
        this._instance = this._instance || new GameStorage();
        return this._instance;
    }

    initData(_unionId = null) {
        if (_unionId === null) {
            // _unionId = UserManger.getInstance().getUserInfo().getUnionId();
        }

        this.InitDefaultData();

        let dataStr = cc.sys.localStorage.getItem(`MoneyGame_GameStorage_${_unionId}`);
        if (!dataStr || dataStr === "") {
            this.clearData();
        } else {
            this.data = JSON.parse(dataStr);
            this.saveData();
        }

        this.SetEveryData();
    }

    // 初始化默认值
    InitDefaultData() {
        this.defaultValue = {
            high_score: 0,
            high_score_lastTime: 0,
            GameData: {},
            unlock_list_role: [0, 1, 2],
            select_index_role: 0,
        };
    }

    SetEveryData() {
        for (let key in this.defaultValue) {
            let defaultValue = this.defaultValue[key];
            let dataValue = this.data[key];
            // console.log(key, defaultValue, dataValue);
            if (dataValue === null || dataValue === undefined) {
                this.data[key] = defaultValue;
            }
        }
        this.saveData();
    }

    clearData() {
        this.data = { ...this.defaultValue };
    }

    saveData(_unionId = null) {
        if (_unionId === null) {
            // _unionId = UserManger.getInstance().getUserInfo().getUnionId();
        }
        let dataStr = JSON.stringify(this.data);
        cc.sys.localStorage.setItem(`MoneyGame_GameStorage_${_unionId}`, dataStr);
    }
}

export default GameStorage.instance;

/** 调试 */
window["GameStorage"] = GameStorage.instance;
// window['GameStorage'] = GameStorage;